from .utils import singleton
import collections
from tkinter import messagebox
import sys


class MsgQueue:
    def __init__(self, key_symbol, name, filter_ids=None, isCanFD=False) -> None:
        self.key_symbol = key_symbol
        self.name = name
        # filter_ids 是过滤器id清单
        if filter_ids is not None:
            self.filter_ids = [int(item, 16) for item in filter_ids]
        self.isCanFD = isCanFD

        # 存放msg的队列
        self.deque = collections.deque(maxlen=100)

        self.open_flag = False

    def open_queue(self):
        self.open_flag = True

    def close_queue(self):
        self.open_flag = False

    def addMsg(self, msg, isCanFD=False):
        '''
        往deque中增加msg
        msg 类型  ZCAN_CAN_FRAME
        '''
        # 不是创建时的isCanFD类型，不处理
        if isCanFD is not self.isCanFD:
            return

        # 未开启接收，不处理
        if self.open_flag is False:
            return

        if self.filter_ids is None:
            self.deque.append(msg)
            # print(f'[file:{__file__}]=>[line:{
            #   (sys._getframe().f_lineno)}]==>{msg.can_id}')
        elif msg.frame.can_id in self.filter_ids:
            # print(f'[file:{__file__}]=>[line:{
            # (sys._getframe().f_lineno)}]==>{msg.can_id}')
            self.deque.append(msg)

    def clear(self):
        self.deque.clear()

    def count(self):
        return len(self.deque)

    def update_filter_ids(self, filter_ids):
        self.filter_ids = filter_ids


@singleton
class Can_UnitTestRecvQueue:

    queue_dict = {}

    def __init__(self) -> None:
        pass

    def create_queue(self, key_symbol, name="未命名", filter_ids=None, isCanFD=False) -> MsgQueue:
        '''
        创建一个queue,要给key_symbol唯一命名
        传入接收的id清单
        '''
        if key_symbol not in self.queue_dict:
            self.queue_dict[key_symbol] = MsgQueue(
                key_symbol, name=name, filter_ids=filter_ids, isCanFD=isCanFD)
        else:
            messagebox.showwarning(
                'warning', f'{key_symbol} queue already exists')
        return self.queue_dict[key_symbol]

    def get_queue(self, key_symbol):
        '''
        获取一个queue
        '''
        if key_symbol not in self.queue_dict:
            messagebox.showwarning(
                'warning', 'queue not exists')
        return self.queue_dict[key_symbol]

    def del_queue(self, key_symbol):
        '''
        删除指定的queue
        '''
        if key_symbol not in self.queue_dict:
            messagebox.showwarning(
                'warning', 'queue not exists')
        else:
            self.queue_dict.pop(key_symbol)

    def append_msg_to_queues(self, msg, isCanFD=False):
        for key in self.queue_dict:
            self.queue_dict[key].addMsg(msg, isCanFD=isCanFD)


global_can_unitTestRecvQueues = Can_UnitTestRecvQueue()
